using System.Net;
using System.Net.Sockets;
using System.Text;
using Newtonsoft.Json;
using Models;
using NLog;

namespace Services
{
    /// <summary>
    /// TCP数据监听器
    /// </summary>
    public class TcpDataListener
    {
        private TcpListener? tcpListener;
        private bool isListening = false;
        private Thread? listenerThread;
        private readonly Logger logger = LogManager.GetCurrentClassLogger();
        private readonly int port;

        /// <summary>
        /// 数据接收事件
        /// </summary>
        public event EventHandler<EmployeeDataReceivedEventArgs>? EmployeeDataReceived;

        public TcpDataListener(int port = 8888)
        {
            this.port = port;
        }

        /// <summary>
        /// 启动TCP监听
        /// </summary>
        public void Start()
        {
            try
            {
                tcpListener = new TcpListener(IPAddress.Any, port);
                tcpListener.Start();
                isListening = true;

                listenerThread = new Thread(ListenForClients)
                {
                    IsBackground = true
                };
                listenerThread.Start();

                logger.Info($"TCP监听器已启动，监听端口: {port}");
            }
            catch (Exception ex)
            {
                logger.Error(ex, $"启动TCP监听器失败，端口: {port}");
                throw;
            }
        }

        /// <summary>
        /// 停止TCP监听
        /// </summary>
        public void Stop()
        {
            try
            {
                isListening = false;
                tcpListener?.Stop();
                listenerThread?.Join(5000); // 等待5秒
                logger.Info("TCP监听器已停止");
            }
            catch (Exception ex)
            {
                logger.Error(ex, "停止TCP监听器时发生错误");
            }
        }

        /// <summary>
        /// 监听客户端连接
        /// </summary>
        private void ListenForClients()
        {
            while (isListening)
            {
                try
                {
                    if (tcpListener?.Pending() == true)
                    {
                        using var client = tcpListener.AcceptTcpClient();
                        HandleClient(client);
                    }
                    Thread.Sleep(100); // 避免CPU占用过高
                }
                catch (Exception ex)
                {
                    if (isListening) // 只有在监听状态下才记录错误
                    {
                        logger.Error(ex, "处理客户端连接时发生错误");
                    }
                }
            }
        }

        /// <summary>
        /// 处理客户端数据
        /// </summary>
        private void HandleClient(TcpClient client)
        {
            try
            {
                using var stream = client.GetStream();
                using var reader = new StreamReader(stream, Encoding.UTF8);

                var jsonData = reader.ReadLine(); // 改用ReadLine，读取一行JSON数据
                
                if (!string.IsNullOrWhiteSpace(jsonData))
                {
                    logger.Info($"接收到数据: {jsonData}");
                    
                    // 解析JSON数据
                    var employeeData = JsonConvert.DeserializeObject<EmployeeData>(jsonData);

                    if (employeeData != null)
                    {
                        // 触发数据接收事件
                        EmployeeDataReceived?.Invoke(this, new EmployeeDataReceivedEventArgs(employeeData));
                        
                        // 发送响应
                        SendResponse(stream, "OK");
                    }
                    else
                    {
                        logger.Warn($"无法解析JSON数据: {jsonData}");
                        SendResponse(stream, "ERROR: Invalid JSON format");
                    }
                }
            }
            catch (JsonException ex)
            {
                logger.Error(ex, "JSON解析错误");
                try
                {
                    SendResponse(client.GetStream(), "ERROR: JSON parse failed");
                }
                catch { }
            }
            catch (Exception ex)
            {
                logger.Error(ex, "处理客户端数据时发生错误");
            }
        }

        /// <summary>
        /// 发送响应给客户端
        /// </summary>
        private void SendResponse(NetworkStream stream, string response)
        {
            try
            {
                using (var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true))
                {
                    writer.WriteLine(response); // 使用WriteLine确保有换行符
                    writer.Flush();
                }
                // 不要手动关闭stream，让using语句自动处理
            }
            catch (Exception ex)
            {
                logger.Error(ex, "发送响应时发生错误");
            }
        }
    }

    /// <summary>
    /// 员工数据接收事件参数
    /// </summary>
    public class EmployeeDataReceivedEventArgs : EventArgs
    {
        public EmployeeData EmployeeData { get; }
        public DateTime ReceiveTime { get; }

        public EmployeeDataReceivedEventArgs(EmployeeData employeeData)
        {
            EmployeeData = employeeData;
            ReceiveTime = DateTime.Now;
        }
    }
}
